
package cn.bx.bid.ctrl;

import cn.bx.bid.entity.Answer;
import cn.bx.bid.entity.Question;
import cn.bx.bid.service.AnswerService;
import cn.bx.bid.service.QuestionService;
import cn.bx.bid.util.AjaxResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class MainController {
    @Resource
    QuestionService qs;

    @Resource
    AnswerService as;

    @RequestMapping(value = "searchAll", produces = "application/json;charset=utf-8")
    public AjaxResult searchAll() {
        List<Question> list = qs.search();
        if (list.size() == 0) {
            return AjaxResult.error("没数据");
        }
        return AjaxResult.success(list);
    }

    @RequestMapping(value = "getBy", produces = "application/json;charset=utf-8")
    public AjaxResult getBy(@RequestParam(name = "id") long id) {
        Question question = qs.get(id);
        if (question == null) {
            return AjaxResult.error();
        }
        return AjaxResult.success(question);
    }

    @RequestMapping(value = "addQuestion", produces = "application/json;charset=utf-8")
    public AjaxResult addQuestion(@RequestBody Question question) {
        int r = qs.save(question);
        if (r == 0) {
            return AjaxResult.error("添加失败");
        }
        return AjaxResult.success("添加成功");
    }

    @RequestMapping(value = "addAnswer", produces = "application/json;charset=utf-8")
    public AjaxResult addAnswer(@RequestBody Answer answer) {
        int r2 =as.save(answer);
        if (r2 == 0) {
            return AjaxResult.error("添加失败");
        }
        return AjaxResult.success("添加成功");
    }

    @RequestMapping(value = "getAnswer", produces = "application/json;charset=utf-8")
    public AjaxResult getAnswer(@RequestParam(name = "qid") long id) {
        Answer answer = as.get(id);
        if (answer == null) {
            return AjaxResult.error();
        }
        return AjaxResult.success(answer);
    }

//    @InitBinder
//    public void initBinder(WebDataBinder binder) {
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
//        // true:允许输入空值，false:不能为空值
//    }
}

